<script setup lang="ts">
import { ref, computed } from "vue";
import { useAdConversion } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useI18n } from "vue-i18n";
import { message } from "@/utils/message";

const { t } = useI18n();

// 图标导入
import Refresh from "@iconify-icons/ep/refresh";
import Search from "@iconify-icons/ep/search";

defineOptions({
  name: "AdConversion"
});

const formRef = ref();
const tableRef = ref();

const {
  form,
  loading,
  columns,
  dataList,
  groupOptions,
  platformOptions,
  payChannelOptions,
  activeTab,
  allTabsData,
  quickSelect,
  sortField,
  sortOrder,
  onSearch,
  resetForm,
  handleTabChange,
  handleSortChange,
  selectTimeRange,
  handleDateChange,
  formatAmount,
  getConversionRateType,
  orderDialogVisible,
  currentOrderData,
  viewOrderDetails,
  closeOrderDialog,
  activeOrderTab
} = useAdConversion();

// 展示组数据的控制开关
const showGroupData = ref(false);

// 过滤后的数据列表
const filteredDataList = computed(() => {
  if (showGroupData.value) {
    // 显示所有数据（投放组 + 投放人员）
    return dataList.value;
  } else {
    // 仅显示投放人员数据
    return dataList.value.filter(item => item.type === 'user');
  }
});

function onFullscreen() {
  // 重置表格高度
  tableRef.value.setAdaptive();
}

// 处理表格排序变化
function onSortChange({ prop, order }) {
  if (prop && ['order_count', 'total_sales', 'total_cost', 'conversion_rate', 'cost_per_order', 'avg_order_value', 'abandoned_orders'].includes(prop)) {
    handleSortChange(prop);
  }
}

// 复制到剪贴板
function copyToClipboard(text: string) {
  navigator.clipboard.writeText(text).then(() => {
    message("已复制到剪贴板", { type: "success" });
  }).catch(() => {
    message("复制失败", { type: "error" });
  });
}

// 自定义合计方法
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];

  // 根据展示设置决定统计哪些数据
  const userItems = data.filter(item => item.type === 'user');
  const shouldShowUserTotal = userItems.length > 0;

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '汇总';
      return;
    }

    if (userItems.length === 0) {
      sums[index] = '';
      return;
    }

    switch (column.property) {
      case 'type':
        sums[index] = '人员合计';
        break;
      case 'name':
        sums[index] = `共${userItems.length}人`;
        break;
      case 'order_count':
        sums[index] = userItems.reduce((sum, item) => sum + item.order_count, 0);
        break;
      case 'total_sales':
        const totalSales = userItems.reduce((sum, item) => sum + item.total_sales, 0);
        sums[index] = `${formatAmount(totalSales)}`;
        break;
      case 'total_cost':
        const totalCost = userItems.reduce((sum, item) => sum + item.total_cost, 0);
        sums[index] = `${formatAmount(totalCost)}`;
        break;
      case 'conversion_rate':
        const sales = userItems.reduce((sum, item) => sum + item.total_sales, 0);
        const cost = userItems.reduce((sum, item) => sum + item.total_cost, 0);
        if (cost === 0) {
          sums[index] = '-';
        } else {
          const rate = sales / cost;
          sums[index] = rate.toFixed(2);
        }
        break;
      case 'cost_per_order':
        const totalOrders = userItems.reduce((sum, item) => sum + item.order_count, 0);
        if (totalOrders === 0) {
          sums[index] = '-';
        } else {
          const totalAdCost = userItems.reduce((sum, item) => sum + item.total_cost, 0);
          const costPerOrder = totalAdCost / totalOrders;
          sums[index] = `${formatAmount(costPerOrder)}`;
        }
        break;
      case 'avg_order_value':
        const orderCount = userItems.reduce((sum, item) => sum + item.order_count, 0);
        if (orderCount === 0) {
          sums[index] = '-';
        } else {
          const orderSales = userItems.reduce((sum, item) => sum + item.total_sales, 0);
          const avgValue = orderSales / orderCount;
          sums[index] = `${formatAmount(avgValue)}`;
        }
        break;
      case 'abandoned_orders':
        sums[index] = userItems.reduce((sum, item) => sum + item.abandoned_orders, 0);
        break;
      default:
        sums[index] = '';
    }
  });

  return sums;
};
</script>

<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="投放组" prop="group_id">
        <el-select
          v-model="form.group_id"
          placeholder="请选择投放组"
          clearable
          class="!w-[180px]"
          filterable
        >
          <el-option
            v-for="group in groupOptions"
            :key="group.value"
            :label="group.label"
            :value="group.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="平台" prop="platform">
        <el-select
          v-model="form.platform"
          placeholder="请选择平台"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="platform in platformOptions"
            :key="platform.value"
            :label="platform.label"
            :value="platform.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围" prop="date_range">
        <el-select v-model="quickSelect" placeholder="选择时间" @change="selectTimeRange" style="width: 103px; border-radius: 0; border-right: 0px">
          <el-option label="今天" value="today" />
          <el-option label="昨天" value="yesterday" />
          <el-option label="最近七天" value="7day" />
          <el-option label="最近30天" value="30day" />
          <el-option label="本月" value="month" />
          <el-option label="上月" value="lastmonth" />
          <el-option label="自定义" value="diy" />
        </el-select>
        <el-date-picker
          v-model="form.date_range"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 300px; border-radius: 0px; border-left: 0; margin-left: -1px"
          @change="handleDateChange"
        />
      </el-form-item>

      <el-form-item label="">
        <el-checkbox v-model="showGroupData">
          显示投放组数据
        </el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch"
        >
          {{ t("buttons.search") }}
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="resetForm(formRef)"
        >
          {{ t("buttons.reset") }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格工具栏 -->
    <PureTableBar
      title="广告转化率统计数据"
      :columns="columns"
      :isExpandAll="false"
      :tableRef="tableRef?.getTableRef()"
      @refresh="onSearch"
      @fullscreen="onFullscreen"
    >
      <template #buttons>
        <!-- 可以在这里添加导出等功能按钮 -->
      </template>

      <template v-slot="{ size, dynamicColumns }">
        <!-- 支付通道切换Tab -->
        <div class="mb-4">
          <el-tabs
            v-model="activeTab"
            @tab-change="handleTabChange"
            class="pay-channel-tabs"
          >
            <el-tab-pane
              v-for="(tabData, tabKey) in allTabsData"
              :key="tabKey"
              :label="`${tabData.label} `"
              :name="tabKey"
            />
          </el-tabs>
        </div>

        <pure-table
          ref="tableRef"
          adaptive
          :adaptiveConfig="{ offsetBottom: 45 }"
          align-whole="center"
          :row-key="(row) => `${row.type}_${row.id}`"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="filteredDataList"
          :columns="dynamicColumns"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :default-sort="{ prop: sortField, order: sortOrder === 'desc' ? 'descending' : 'ascending' }"
          @sort-change="onSortChange"
          show-summary
          :summary-method="getSummaries"
        />
      </template>
    </PureTableBar>

    <!-- 订单查看弹窗 -->
    <el-dialog
      v-model="orderDialogVisible"
      :title="`${currentOrderData.name} 的订单列表`"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      @close="closeOrderDialog"
      class="order-dialog"
    >
      <el-tabs v-model="activeOrderTab" type="card">
        <!-- 普通订单Tab -->
        <el-tab-pane
          name="dcl"
          :label="`普通订单 (${currentOrderData.orders_dcl_list.length})`"
          :disabled="currentOrderData.orders_dcl_list.length === 0"
        >
          <div v-if="currentOrderData.orders_dcl_list.length > 0">
            <!-- 复制按钮 -->
            <div style="margin-bottom: 16px; text-align: right;">
              <el-button
                type="success"
                @click="copyToClipboard(currentOrderData.orders_dcl_list.join(', '))"
              >
                复制普通订单
              </el-button>
            </div>
            <!-- 订单内容 -->
            <div style="line-height: 2; font-size: 14px;">
              <div
                style="
                  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
                  background: #f5f7fa;
                  padding: 16px;
                  border-radius: 6px;
                  color: #67C23A;
                  word-break: break-all;
                  white-space: pre-wrap;
                  min-height: 200px;
                  max-height: 400px;
                  overflow-y: auto;
                "
              >
                {{ currentOrderData.orders_dcl_list.join(', ') }}
              </div>
            </div>
          </div>
          <div v-else style="text-align: center; padding: 40px;">
            <el-empty description="暂无普通订单数据" />
          </div>
        </el-tab-pane>

        <!-- 弃单订单Tab -->
        <el-tab-pane
          name="qd"
          :label="`弃单订单 (${currentOrderData.orders_qd_list.length})`"
          :disabled="currentOrderData.orders_qd_list.length === 0"
        >
          <div v-if="currentOrderData.orders_qd_list.length > 0">
            <!-- 复制按钮 -->
            <div style="margin-bottom: 16px; text-align: right;">
              <el-button
                type="warning"
                @click="copyToClipboard(currentOrderData.orders_qd_list.join(', '))"
              >
                复制弃单订单
              </el-button>
            </div>
            <!-- 订单内容 -->
            <div style="line-height: 2; font-size: 14px;">
              <div
                style="
                  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
                  background: #f5f7fa;
                  padding: 16px;
                  border-radius: 6px;
                  color: #E6A23C;
                  word-break: break-all;
                  white-space: pre-wrap;
                  min-height: 200px;
                  max-height: 400px;
                  overflow-y: auto;
                "
              >
                {{ currentOrderData.orders_qd_list.join(', ') }}
              </div>
            </div>
          </div>
          <div v-else style="text-align: center; padding: 40px;">
            <el-empty description="暂无弃单订单数据" />
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeOrderDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.main {
  margin: 0;
  padding: 0;
}

.search-form {
  margin-bottom: 16px;
}

:deep(.el-form-item) {
  margin-bottom: 12px;
}

.pay-channel-tabs {
  margin-bottom: 16px;
}

:deep(.pay-channel-tabs .el-tabs__header) {
  margin-bottom: 0;
}

:deep(.pay-channel-tabs .el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: var(--el-border-color-light);
}

/* 订单弹窗样式 */
:deep(.order-dialog) {
  max-height: 85vh;
}

:deep(.order-dialog .el-dialog__body) {
  max-height: 60vh;
  overflow: hidden;
}

:deep(.order-dialog .el-tabs__content) {
  max-height: 55vh;
  overflow: hidden;
}

:deep(.order-dialog .el-tab-pane) {
  max-height: 50vh;
  overflow: hidden;
}
</style>
